package com.compass.mobile.framework.utils

import android.hardware.Camera
import android.os.Build
import android.util.Log

/*
 *作者:赵星海
 *时间:2021/3/23 15:44
 *用途:是否有可用摄像头
 */
fun isCamera(): Boolean {
    var result: Boolean
    var camera: android.hardware.Camera? = null
    try {
        camera = Camera.open()
        if (camera == null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD) {
            var connected = false
            for (camIdx in 0 until Camera.getNumberOfCameras()) {
                Log.d("TAG", "Trying to open camera with new open(" + Integer.valueOf(camIdx) + ")")
                try {
                    camera = Camera.open(camIdx)
                    connected = true
                } catch (e: RuntimeException) {
                    Log.e("TAG", "Camera #" + camIdx + "failed to open: " + e.localizedMessage)
                }
                if (connected) {
                    break
                }
            }
        }
        val supportedPreviewSizes: List<Camera.Size> = camera?.getParameters()?.getSupportedPreviewSizes() as List<Camera.Size>
        result = supportedPreviewSizes != null
        //start the preview
        Log.d("TAG", "startPreview")
        camera?.startPreview()
    } catch (e: java.lang.Exception) {
        Log.e("TAG", "Camera is not available (in use or does not exist): " + e.localizedMessage)
        result = false
    } finally {
        if (camera != null) {
            camera.release()
        }
    }
    return result
}